/**
 * 对提供slb服务的健康检查
 */
void health (){

try {
    String res =  sh(script: """
                        # 使用 Jenkins 提供的临时密钥文件路径
                  curl --request GET -m 10  --url http://172.16.5.6:8999/health 
                    """,returnStdout: true)
    println("slb健康检查结果:${res}")
    if(res.contains("healthy")){
        println("✅slb健康检查通过")
    }else{
        error "❌slb健康检查失败"
    }
}catch (Exception e){
    error "❌slb健康检查失败"
}
}

/**
 * 修改slb权重
 * @param regionId
 * @param vserverGroupId
 * @param ip
 * @param serverId
 * @param weight
 */
void  editweight(String regionId,String vserverGroupId,String ip,String serverId,String weight){
    try {
    String param="""{
    "region_id": "${regionId}", 
    "vserver_group_id": "${vserverGroupId}", 
    "backend_servers": [
        {
            "ServerId": "${serverId}",
            "Weight": "${weight}",
            "ServerIp": "${ip}"
        }
    ]
    }"""
    String res =  sh(script: """
                        # 使用 Jenkins 提供的临时密钥文件路径
                  curl --request POST \\
                  --header 'Content-Type: application/json' \\
                 -m 10  --url http://172.16.5.6:8999/set-vserver-group \\
                 --data  '${param}'
                    """,returnStdout: true)
    println("slb修改权重结果:${res}")
    if(res.contains("设置成功")){
        println("✅slb修改权重成功")
    }else{
        error "❌slb修改权重失败"
    }
}catch (Exception e){
    error "❌slb修改权重失败"
}
}
/**
 * 服务下线
 * @param projectName
 * @param branch
 * @param regionId
 * @param vserverGroupId
 * @param ip
 */
void down(String projectName,String branch,String regionId,String vserverGroupId,String ip){
    String serverId=getServerId(projectName,branch,ip)
    editweight(regionId,vserverGroupId,ip,serverId,"0")
    sleep(60)
}
/**
 * 服务上线
 * @param projectName 项目名
 * @param branch    分支名
 * @param regionId
 * @param vserverGroupId
 * @param ip
 */
void up(String projectName,String branch,String regionId,String vserverGroupId,String ip){
    String serverId=getServerId(projectName,branch,ip)
    editweight(regionId,vserverGroupId,ip,serverId,"100")
}

/**
 * 获取serverId
 * @param projectName
 * @param branch
 * @param ip
 * @return
 */
String getServerId(String projectName,String branch,String ip){
    String filePath = "/var/jenkins_home/slb/${projectName}/${branch}"
    String serverId= ""
    List<String> lines = sh(
            script: "cat  ${filePath}",
            returnStdout: true
    ).trim().split('\n')
    for (String line in lines) {
        if (line.contains(ip)) {
            String[] strs = line.split("\\|\\|")
            serverId= strs[1].trim()
        }
    }
    if (util.strIsBlack(serverId)) {
        error "没有找到${ip}对应的serverId"
    }
    return serverId
}

